package com.skyworth.badsdk;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.skyworth.framework.skysdk.android.SkySystemUtil;
import com.skyworth.framework.skysdk.android.SkySystemUtil.LINUX_CMD;
import com.skyworth.framework.skysdk.logger.Logger;

public class SkyHttpDownloader extends SkyDownloader {
    URL url = null;
    HttpURLConnection connection = null;
    String downloadPath = "./";
    final static String lineEnd = "\r\n";
    final static String twoHyphens = "--";
    final static String boundary = "*****";
    private final int FILE_MAX_LENGTH = 254;
    private final String GBK = "GBK";
    private final String UTF_8 = "UTF-8";

    int downloadID = 0;
    String currentDownloadURL = null;
    String realDownloadURL = null;
    boolean downloadCanceled = false;
    private boolean downloadPaused = false;

    private File localFile = null;
    private long rfPosit = 0;
    private int resumeFileLength = 0;
    private String locallocation = null;
    private boolean isCreatePathSuccess = true;
    private boolean isUTF8 = false;

    private String gRename = null;

    public SkyHttpDownloader(SkyDownloadListener listener) {
        super(listener);
        String downloadCache = CoocaaApplication.getContext().getCacheDir().getAbsolutePath();// SkyGeneralProperties.SKY_DIR;
        // if (downloadCache == null)
        // {
        // downloadCache = SkyGeneralProperties.SKY_DIR + "/download_cache";
        // }
        // SkySystemUtil.execCmd(LINUX_CMD.LINUX_CMD_CHMOD, " 777 " + downloadCache);
        setDownloadPath(downloadCache);
        // setDownloadPath("/home/guiqingwen/");
    }

    /**
     * @return String
     * @Description 鑾峰彇涓嬭浇鏂囦欢鐨勭粷瀵硅矾寰�
     * @date 2012-8-30
     */
    public String getAbsluteFilePath() {
        return locallocation;
    }

    public void setDownloadPath(String path) {
        downloadPath = path;
        Logger.i("downloadPath = " + downloadPath);
        File downloadDir = new File(downloadPath);
        if (!downloadDir.exists()) {
            if (!downloadDir.mkdirs()) {
                Logger.error("Create download folder failed:" + path);
                isCreatePathSuccess = false;
            }
        }
        downloadPath = downloadDir.getAbsolutePath() + File.separator;
        Logger.i("succeeded to generate download folder:" + downloadPath);
    }

    private boolean downloadURL(String remoteurl) throws Exception {
        realDownloadURL = getRealUrl(remoteurl);
        System.out.println("downloadURL url = " + remoteurl);

        if (!initConnection() || !checkResponseCode()) {
            downListener.onFailed(SkyDownloadErrorMessage.ConnectError);
            return false;
        }

        String filename = getFileNameAll();
        fileName = filename;
        if (filename == null || filename.equals("")) {
            Logger.e("filename is null ");
            // FIXME: set a default name
            downListener.onFailed(SkyDownloadErrorMessage.FileNameError);
            return false;
        }

        int fileLength = connection.getContentLength();
        System.out.println("filename = " + filename + ", Length = " + fileLength);
        if (!hasSufficientSpace(fileLength)) {
            Logger.e("no more space");

            downListener.onFailed(SkyDownloadErrorMessage.NoMoreSpace);
            return false;
        }

        filename = downloadPath + filename;
        locallocation = filename;
        if (downListener != null) {
            downListener.onStarted(locallocation);
        }

        if (gRename != null && !gRename.equals("")) {
            writeRecord();
        }

        File downfile = createFile(filename);
        // FileOutputStream output = new FileOutputStream(downfile);
        RandomAccessFile output = new RandomAccessFile(downfile, "rw"); // FIXME:鏁堢巼闂

        int totalDownloadLen = down(output, fileLength);
        if (totalDownloadLen < fileLength) {
            System.out.println("Download canceled");
            if (downloadCanceled) {
                deleteRecord();
                deleteDownFile(locallocation);
                downListener.onFailed(SkyDownloadErrorMessage.CancelError);
            } else {
                downListener.onFailed(SkyDownloadErrorMessage.PauseError);
            }
            return false;
        }

        readRecord();
        deleteRecord();
        if (gRename != null && !gRename.equals("")) {
            reductionFileName();
        }

        if (downListener != null) {
            SkySystemUtil.execCmd(LINUX_CMD.LINUX_CMD_CHMOD, " 777 " + locallocation);
            downListener.onFinished(locallocation);
        }
        return true;
    }

    private int down(RandomAccessFile output, int fileLength) throws IOException,
            FileNotFoundException {
        byte[] buffer = new byte[1024];
        Logger.i("connection.getInputStream()..");
        InputStream in = connection.getInputStream();
        int totalDownloadLen = (int) output.length();

        Logger.i("totalDownloadLen=" + totalDownloadLen + " filelen=" + fileLength
                + " filelocation=" + locallocation);
        totalDownloadLen = (int) SkySystemUtil.getFileSize(locallocation);
        Logger.i("totalDownloadLen=" + totalDownloadLen + " filelen=" + fileLength
                + " filelocation=" + locallocation);
        downloadCanceled = false;

        int readBytesLen = in.read(buffer);
        while (readBytesLen > 0) {
            if (downloadCanceled) {
                break;
            } else if (downloadPaused) {
                // try
                // {
                // Thread.sleep(100);
                // } catch (InterruptedException e)
                // {
                // // TODO Auto-generated catch block
                // e.printStackTrace();
                // }
                // continue;
                break;
            } else {
                output.write(buffer, 0, readBytesLen);

                totalDownloadLen += readBytesLen;
                if (downListener != null) {
                    downListener.onDownloaded(totalDownloadLen, fileLength);
                    if (fileLength > 0) {
                        float procent = (float) totalDownloadLen / (float) fileLength;
                        // downListener.onDownloaded(procent, 0, 0);
                        if (procent >= 1.0f) {
                            break;
                        }
                    }
                }
                readBytesLen = in.read(buffer);
            }
        }
        output.close();
        connection.disconnect();
        return totalDownloadLen;
    }

    public void download() {
        try {
            downloadURL(currentDownloadURL);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error("Download url error:" + e.toString());
            if (downListener != null) {
                downListener.onFailed(e.toString());
            }
        }
    }

    public void pause() {
        downloadPaused = true;
    }

    public void resume() {
        downloadPaused = false;
        downloadCanceled = false;
        Logger.i("-------------resume");
        try {
            resumeDownload(currentDownloadURL);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Logger.i("resumeDownload　Error" + e.toString());
            if (downListener != null) {
                downListener.onFailed(SkyDownloadErrorMessage.OtherException);
            }
        }
    }

    // private void resumeDownloadFromUrl(String downloadUrl)
    // {
    // try
    // {
    // resumeDownload(downloadUrl);
    // } catch (Exception e)
    // {
    // e.printStackTrace();
    // Logger.e("resumeDownloadFromUrl error" + e.getMessage());
    // if (downListener != null)
    // {
    // downListener.onFailed(e.toString());
    // }
    // }
    // }

    private void resumeDownload(String downloadUrl) throws Exception {
        realDownloadURL = getRedirectUrl(downloadUrl);

        if (!initConnection()) {
            downListener.onFailed(SkyDownloadErrorMessage.ConnectError);
            return;
        }

        String filename = getFileNameAll();
        Logger.i("resumeDownload, getFileNameAll = " + filename);
        fileName = filename;

        if (filename == null || filename.equals("")) {
            Logger.e("filename is null ");
            // FIXME: set a default name
            downListener.onFailed(SkyDownloadErrorMessage.FileNameError);
            return;
        }
        Logger.i("resumeDownload, getFileNameAll = " + filename);
        locallocation = downloadPath + filename;
        localFile = new File(locallocation);
        rfPosit = getFileSize(localFile);
        resumeFileLength = (int) rfPosit;

        connection.disconnect();
        if (!initResumeConnection() || !checkResumeResponseCode()) {
            downListener.onFailed(SkyDownloadErrorMessage.ConnectError);
            return;
        }
        //

        int fileLength = connection.getContentLength();
        if (fileLength == resumeFileLength) // FIXME, fileLength == 0, then finished
        {
            if (downListener != null) {
                downListener.onFinished(locallocation);
            }
            return;
        }
        System.out.println("ed = " + resumeFileLength + ", ing = " + fileLength + ", all = "
                + (resumeFileLength + fileLength));

        if (!hasSufficientSpace(fileLength)) {
            Logger.e("no more space");
            downListener.onFailed(SkyDownloadErrorMessage.NoMoreSpace);
            return;
        }

        if (downListener != null) {
            downListener.onStarted(locallocation);
        }

        RandomAccessFile fileOut = new RandomAccessFile(localFile, "rw");
        fileOut.seek(fileOut.length());

        int totalLength = -1;
        if (fileLength > 0) {
            totalLength = fileLength + resumeFileLength;
        }
        Logger.i("downloading....");
        int downLength = down(fileOut, totalLength);

        if (downLength < totalLength) {
            System.out.println("Download canceled");
            if (downloadCanceled) {
                deleteRecord();
                deleteDownFile(locallocation);
                downListener.onFailed(SkyDownloadErrorMessage.CancelError);
            } else {
                downListener.onFailed(SkyDownloadErrorMessage.PauseError);
            }
            return;
        }
        if (null == gRename || gRename.equals("")) {
            readRecord();
        }
        deleteRecord();
        if (gRename != null && !gRename.equals("")) {
            reductionFileName();
        }

        if (downListener != null) {
            SkySystemUtil.execCmd(LINUX_CMD.LINUX_CMD_CHMOD, " 777 " + locallocation);
            downListener.onFinished(locallocation);
        }
        return;
    }

    private boolean initConnection() throws IOException {
        Logger.i("initConnection, url = " + realDownloadURL);
        url = new URL(realDownloadURL);
        if (url != null) {
            connection = (HttpURLConnection) url.openConnection();
            if (connection != null) {
                // connection.setRequestMethod("GET");
                // connection.setDoOutput(true);
                connection.setReadTimeout(20000);
                connection.setConnectTimeout(20000);
                // connection.setRequestProperty("RANGE", "bytes=" + rfPosit + "-");
                // return connection.getResponseCode();
                return true;
            }
        }
        return false;
    }

    private boolean initResumeConnection() throws IOException {
        Logger.i("initResumeConnection, url = " + realDownloadURL);
        URL mUrl = new URL(realDownloadURL);
        if (mUrl != null) {
            connection = (HttpURLConnection) mUrl.openConnection();
            if (connection != null) {
                // connection.setRequestMethod("GET");
                // connection.setDoOutput(true);
                connection.setRequestProperty("RANGE", "bytes=" + rfPosit + "-");
                connection.setReadTimeout(20000);
                connection.setConnectTimeout(20000);
                // connection.setRequestProperty("RANGE", "bytes=" + rfPosit + "-");
                // return connection.getResponseCode();
                return true;
            }
        }
        return false;
    }

    private boolean checkResponseCode() throws IOException {
        for (int i = 0; i < 2; i++) {
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return true;
            }
        }
        return false;
    }

    private boolean checkResumeResponseCode() throws IOException {
        for (int i = 0; i < 2; i++) {
            Logger.i("connection.getResponseCode()=" + connection.getResponseCode());
            if (connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL
                    || connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return true;
            }
        }
        return false;
    }

    private boolean hasSufficientSpace(int fileLength) {
        long memorySpace = SkySystemUtil.getAvailSpace(downloadPath);
        Logger.info("memorySpace == " + memorySpace);
        if (memorySpace < fileLength + 1024 * 1024) {
            if (connection != null) {
                connection.disconnect();
            }
            return false;
        }

        return true;
    }

    @SuppressWarnings("resource")
    private long getFileSize(File f) throws Exception {
        long s = 0;
        if (f.exists()) {
            FileInputStream fiStream = new FileInputStream(f);
            s = fiStream.available();
        }
        return s;
    }

    public String getDownloadPath() {
        return downloadPath;
    }

    public boolean isFilePathExsit() {
        return isCreatePathSuccess;
    }

    private String getFileName(String url) {
        String filename = "";
        int seperatorPos = url.lastIndexOf("/");
        if (seperatorPos > 0) {
            filename = url.substring(seperatorPos + 1, url.length());
        }
        seperatorPos = filename.lastIndexOf("?");
        if (seperatorPos > 0) {
            filename = filename.substring(0, seperatorPos);
        }
        return filename;
    }

    public String getRedirectUrl(String downUrl) {
        String urlString = null;
        try {
            Logger.i("getRedirectUrl originurl:" + downUrl);
            urlString = getRealUrl(downUrl);
            Logger.i("getRedirectUrl :" + urlString);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error("getRedirectUrl error:" + e.toString());
            if (downListener != null) {
                downListener.onFailed(e.toString());
            }
        }
        return urlString;
    }

    private String getRealUrl(String downUrl) throws Exception {
        URL url = new URL(downUrl);
        // System.out.println("pic url :" + url.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // connection.setDoOutput(true);
        // connection.setRequestMethod("GET");
        connection.setReadTimeout(20000);
        connection.setConnectTimeout(20000);
        connection.getResponseCode();
        String redirectUrl = connection.getURL().toString();
        if (redirectUrl.equals("")) {
            connection.disconnect();
            return downUrl;
        }
        if (connection != null) {
            connection.disconnect();
        }

        return redirectUrl;
    }

    /**
     * @return file name
     * @throws UnsupportedEncodingException
     * @Description 鏂囦欢鍚嶏細鍏堝皾璇曚粠Header澶磋幏鍙栵紝鍐嶄粠URL涓埅鍙栥� TODO: it should be removed from here and
     * make a header parser
     * @date 2012-8-15
     */
    private String getFileNameAll() throws UnsupportedEncodingException {
        String tFileName = null;

        System.out.println(connection.getHeaderFields()); // just for debug
        String contentDisp = connection.getHeaderField("Content-Disposition");
        String type = connection.getHeaderField("Content-Type");
        if (contentDisp != null && contentDisp.contains("filename")) {
            tFileName = getFileNameFromHeader(contentDisp);
        }
        System.out.println("tFileName = " + tFileName);

        if (needUpdateFileName(tFileName)) {
            tFileName = getFileNameFromUrl(connection.getURL().toString());
            // tFileName = getFileNameFromUrl(url2);
            // System.out.println("filename = " + tFileName);
        }

        if (tFileName != null) {
            if (!isUTF8) {
                String result = changeEncoding(connection, tFileName);
                if (result != null && !result.equals("")) {
                    tFileName = result;
                }
                // System.out.println(".. = " + tFileName);
            }

            // tFileName = cutQuotes(tFileName);

            if (tFileName.length() > FILE_MAX_LENGTH) {
                tFileName = cutFileName(tFileName);
            }
            tFileName = checkContentType(tFileName, type);
        }

        return tFileName;
    }

    private String checkContentType(String filename, String type) {
        if (filename.contains(".")) {
            return filename;
        } else {
            if (type != null && type.equals("image/jpeg")) {
                filename = filename + ".jpg";
            }
        }
        return filename;
    }

    /**
     * @param conn
     * @param input 寰呯紪鐮佺殑瀛楃涓�
     * @return 缂栫爜鍚庣殑瀛楃涓�
     * @throws UnsupportedEncodingException String
     * @Description 瀵瑰瓧绗︿覆锛堟枃浠跺悕锛夎浆鐮侊紝浠嶩ttpURLConnection鐨凥eader涓幏鍙栫紪鐮佷俊鎭紝榛樿浣跨敤GBK
     * @date 2012-8-15
     */
    private String changeEncoding(HttpURLConnection conn, String input)
            throws UnsupportedEncodingException {
        // return new String(inputHtml.getBytes("ISO-8859-1"), "Shift_JIS");
        String encode = null;
        String header = conn.getHeaderField("Content-Type");
        // System.out.println("Content-Type: " + header);
        if (header != null) {
            int pos = header.indexOf("charset");
            if (pos > 0) {
                encode = header.substring(pos + "charset".length() + 1);
            }
        }
        if (encode == null || encode.equals("")) {
            encode = GBK;
        }
        // System.out.println(">> encode = " + encode);
        return new String(input.getBytes("ISO-8859-1"), encode);
    }

    /**
     * @param fileName
     * @return boolean
     * @Description 鏄惁闇�閲嶆柊鑾峰彇鏂囦欢鍚嶏紝鏍规嵁宸叉湁鐨勬枃浠跺悕鍚庣紑鍒ゆ柇
     * @date 2012-8-15
     */
    private boolean needUpdateFileName(String fileName) {
        if (fileName != null) {
            String suffix = getSuffix(fileName);
            // System.out.println("suffix = " + suffix);
            if (suffix != null && suffix.length() > 2 && suffix.length() < 6) {
                return false;
            }
        }
        return true;
    }

    private File createFile(String filename) throws IOException {
        File downfile = new File(filename);
        if (downfile.exists()) {
            downfile.delete();
        }
        downfile.createNewFile(); // FIXME: check return value, createNewFile()
        return downfile;
    }

    private String cutFileName(String filename) {
        String suffix = getSuffix(filename);
        if (suffix != null) {
            if (filename.length() > FILE_MAX_LENGTH) {
                filename = filename.substring(0, FILE_MAX_LENGTH - suffix.length());
                filename = filename + suffix;
            }
        }
        return filename;
    }

    /**
     * @param filename
     * @return String
     * @Description 鍘绘帀filename澶淬�灏剧殑鍙屽紩鍙�
     * @date 2012-8-13
     */
    private String cutQuotes(String filename) {
        if (filename != null) {
            if (filename.startsWith("\"")) {
                filename = filename.substring(1);
            }
            if (filename.endsWith("\"")) {
                filename = filename.substring(0, filename.length() - 1);
            }
        }
        return filename;
    }

    private String getSuffix(String fileName) {
        String suffix = null;
        int pos = fileName.lastIndexOf(".");
        if (pos > 0) {
            suffix = fileName.substring(pos);
        }
        return suffix;
    }

    private String getFileNameFromHeader(String contentDisp) throws UnsupportedEncodingException {
        String filename = "";
        // System.out.println("contentDisp = " + contentDisp);
        int endPos = contentDisp.indexOf("UTF-8''");
        if (endPos > 0) {
            filename = decodeUTF8(contentDisp.substring(endPos + 7));
        } else {
            int fileNamePos = contentDisp.indexOf("filename");
            if (fileNamePos != -1) {
                filename = contentDisp.substring(fileNamePos + 9);
                if (filename.contains("%")) {
                    filename = decodeUTF8(filename);
                }
            }
        }
        // System.out.println(">> filename = " + filename);
        return filename;
    }

    private String decodeUTF8(String str) throws UnsupportedEncodingException {
        isUTF8 = true;
        return URLDecoder.decode(str, UTF_8); // 鍏跺畠缂栫爜锛屽GBK绛�
    }

    private String getFileNameFromUrl(String url) throws UnsupportedEncodingException {
        String filename = "";

        int position = url.indexOf("filename");
        if (position > -1) {
            // filename = decodeUTF8(url.substring(position + 9));
            filename = url.substring(position + 9);
            if (filename != null && filename.contains(".")) {
                if (filename.contains("%")) {
                    filename = decodeUTF8(filename);
                }
                return filename;
            }
        }

        int seperatorPos = url.lastIndexOf("/");
        if (seperatorPos > 0) {
            filename = url.substring(seperatorPos + 1, url.length());
        }
        seperatorPos = filename.lastIndexOf("?");
        if (seperatorPos > 0) {
            filename = filename.substring(0, seperatorPos);
        }
        if (filename.contains("%")) {
            filename = decodeUTF8(filename);
        }

        return filename;
    }

    public static void main(String[] args) {
        // float f = 1.2f;
        // int memory = 1200;
        // int filelen = 354;
        // float a = (filelen*f);
        // System.out.println("a=" + a);
        // if(memory < (filelen*f)){
        // System.out.println("ddd");
        // }
        //

        // final SkyHttpDownloader downloader = new SkyHttpDownloader(new SkyDownloadListener()
        // {
        // int count = 0;
        //
        // public void onDownloaded(float finishedLen, float totalLen)
        // {
        // // if (count % 100 == 0)
        // {
        // System.out.println("finished = " + finishedLen);
        // }
        // count++;
        // }
        //
        // public void onFailed(String error)
        // {
        // System.out.println("onFailed:" + error);
        // }
        //
        // public void onFinished(String downloadedFile)
        // {
        // System.out.println("Finished:" + downloadedFile);
        // }
        //
        // @Override
        // public void onStarted(String path)
        // {
        // // TODO Auto-generated method stub
        //
        // }
        // });
        // downloader.setDownloadUrl("http://www.anyview.net/released/android/2.3/Anyview_2.3.apk");
        // downloader.setDownloadPath("E:\\downloadtest\\");
        // downloader.setDownloadFileName("gsf");
        //
        final SkyHttpDownloader downloader = new SkyHttpDownloader(new SkyDownloadListener() {
            int count = 0;

            public void onDownloaded(float finishedLen, float totalLen) {
                // if (count % 100 == 0)
                {
                    System.out.println("finished = " + finishedLen);
                }
                count++;
            }

            public void onFailed(String error) {
                System.out.println("onFailed:" + error);
            }

            public void onFinished(String downloadedFile) {
                System.out.println("Finished:" + downloadedFile);
            }

            @Override
            public void onStarted(String path) {
                // TODO Auto-generated method stub

            }
        });
        downloader.setDownloadUrl("http://www.anyview.net/released/android/2.3/Anyview_2.3.apk");
        downloader.setDownloadPath("G:\\");
        downloader.setDownloadFileName("Anyview_2.3");

        new Thread() {
            public void run() {
                downloader.download();
                // downloader.resume();
            }
        }.start();

        // new Thread(){
        // public void run()
        // {
        // downloader.download();
        // // downloader.resume();
        // }
        // }.start();
        //
        // new Thread(){
        // public void run()
        // {
        // try
        // {
        // Thread.sleep(2000);
        // } catch (InterruptedException e)
        // {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // System.out.println("******************");
        // downloader.pause();
        // }
        // }.start();
        /*
         * try { //downloader.download("http://172.20.28.239/sns/url.ashx?pic=MTU="); //
         * downloader.download
         * ("http://223.4.90.186/apk/4/12022109451020111201221312AhZk.Yyky.V1.2.apk");
         * downloader.download
         * ("http://img842.ph.126.net/99juLRm7NHHzhSNunDUTHg==/1858297796245735112.jpg"); } catch
         * (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try {
         * Thread.sleep(1000); } catch (InterruptedException e) { } // downloader.pause(); try {
         * Thread.sleep(10000); } catch (InterruptedException e) { }
         */
        // downloader
        // .resumeDownloadFromUrl("http://img842.ph.126.net/99juLRm7NHHzhSNunDUTHg==/1858297796245735112.jpg");

        // downloader.download("http://dl.google.com/android/android-sdk_r20-linux.tgz");
        // final String top100 =
        // "http://www.top100.cn/download/dl.php?n=%E8%BF%99%E8%AF%A5%E6%AD%BB%E7%9A%84%E7%88%B1.mp3&al=sgr4ukpbtgy";
        // final String anyview = "http://www.anyview.net/released/android/2.3/Anyview_2.3.apk";
        // final String sogou1 = "http://120.35.4.23/data/mp3/%c4%e3%b5%c4%b1%b3%b0%fc.mp3";
        // final String sogou2 =
        // "http://bt.sheldons.info/COFFdD0xMzQ0Njc1MzI4Jmk9MTEzLjEwNi43OS4xOTMmdT1Tb25ncy92MS9mYWludFFDLzg2LzM3NDZmZjU0ZGM4NWIzYmQyZWM0ZGM2NjYxZTRkYzg2Lm1wMyZtPTQxNmNjZWRlNzgwNGQ2NTA0MWEzYTlkY2Q5Y2U4NGUzJnY9bGlzdGVuJm49pd2ly6lgpcapYKXrpMilt6Xlpbel5SZzPUFLQjQ4JnA9cw==.mp3";
        // final String sogou3 =
        // "http://bbs.roboo.com/attachments/month_0709/xOO1xLGzsPw=_2aL7t3n79Ope.mp3?stdfrom=3";
        // final String sogou4 = "http://www.fzqsng.net/Data/MP3/%C4%E3%B5%C4%B1%B3%B0%FC.mp3";
        // final String srt1 =
        // "http://rs.skyworth-cloud.com/rsmanager/kuaipan.php?id=0349d9146fd|0240298dd18|070bbcfc577";
        // final String sdk = "http://dl.google.com/android/android-sdk_r20.0.3-linux.tgz";
        // final String lrc = "http://www.9ilrc.com/lrc.php?id=29134&uid=3074";
        // final String icon = "http://res.mfs.ykimg.com/050D000051149B7197927302EB0C0D04";
        //
        // long time = System.currentTimeMillis();
        // downloader.download(icon);
        // // downloader.resumeDownloadFromUrl(top100);
        // System.out.println("time: " + (System.currentTimeMillis() - time));
    }

    @Override
    public void setDownloadUrl(String url) {
        // TODO Auto-generated method stub
        if (null == url) {
            url = "";
        }
        currentDownloadURL = url;
    }

    @Override
    public void setDownloadFileName(String name) {
        // TODO Auto-generated method stub
        if (null != name) {
            if (name.equals("") || name.contains("\\") || name.contains("/") || name.contains(":")
                    || name.contains("*") || name.contains("?") || name.contains("<")
                    || name.contains(">") || name.contains(" ") || name.length() > FILE_MAX_LENGTH) {
                Logger.i("file name :" + name + " illegal");
                return;
            }
            gRename = name;
        }
    }

    @Override
    public void deleteDownload() {
        // TODO Auto-generated method stub
        if (downloadPaused || downloadCanceled) {
            deleteRecord();
            deleteDownFile(locallocation);
            downListener.onFailed(SkyDownloadErrorMessage.CancelError);
            return;
        } else {
            downloadCanceled = true;
        }
    }

    private void deleteDownFile(String fileAbsolutionPath) {
        if (fileAbsolutionPath != null) {
            File file = new File(fileAbsolutionPath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    private String fileName = "";

    private String tmpSuffix = "";

    private boolean reductionFileName() {
        if (locallocation != null) {
            File file = new File(locallocation);
            if (file.exists()) {
                if (gRename != null && !gRename.equals("")) {
                    if (fileName != null) {
                        int index = fileName.lastIndexOf(".");
                        String suffix = "";
                        if (index != -1) {
                            suffix = fileName.substring(index); // 宸茬粡鍖呭惈浜嗙偣
                        }
                        String rename = file.getParent() + File.separator + gRename + suffix;
                        if (rename.equals(locallocation)) {
                            return true;
                        }
                        File file2 = new File(file.getParent() + File.separator + gRename + suffix);
                        if (file2.exists()) {
                            file2.delete();
                        }
                        if (file.renameTo(file2)) {
                            fileName = gRename + suffix;
                            locallocation = file.getParent() + File.separator + gRename + suffix;
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private void writeRecord() {
        SkyRecordInfo info = new SkyRecordInfo();
        info.fileName = gRename;
        info.realLength = 0;
        info.url = currentDownloadURL;
        info.completeLength = 0;
        RecordDownInfo.writeRecord(locallocation, info.toString());
    }

    private int readRecord() {
        SkyRecordInfo info = RecordDownInfo.readRecord(locallocation);
        if (info.fileName != null && !"null".equals(info.fileName)) {
            gRename = info.fileName;
        }
        return info.realLength;
    }

    private void deleteRecord() {
        RecordDownInfo.deleteRecord(locallocation);
    }

}
